package com.lb.shopguide.ui.fragment.boss;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterStaff;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.shop.StaffBean;
import com.lb.shopguide.entity.shop.StoreBean;
import com.lb.shopguide.event.boss.AddGuideEvent;
import com.lb.shopguide.event.boss.EditShopEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2018/1/2.
 */

public class FragmentStoreDetail extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.layout_add_shop_manager)
    RelativeLayout layoutAddShopManager;
    @BindView(R.id.layout_store_detail)
    LinearLayout layoutStoreDetail;
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_addr)
    TextView tvShopAddr;
    @BindView(R.id.tv_shop_phone)
    TextView tvPhone;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;

    private AdapterStaff mAdapterStaff;

    private ArrayList<StaffBean> mStaffList;
    private StoreBean storeBean;



    public static FragmentStoreDetail newInstance(StoreBean storeBean) {
        FragmentStoreDetail fragmentStoreDetail = new FragmentStoreDetail();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.STORE_BEAN, storeBean);
        fragmentStoreDetail.setArguments(bundle);
        return fragmentStoreDetail;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_store_detail;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        mStaffList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.STORE_BEAN)) {
            storeBean = (StoreBean) bundle.getSerializable(AppConstant.STORE_BEAN);
        }
        if (storeBean != null) {
            initRequest();
        }
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无员工信息");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterStaff = new AdapterStaff(R.layout.item_staff, mStaffList);
        mRecyclerView.setAdapter(mAdapterStaff);
        mAdapterStaff.setOnStaffQuitClickListener(new AdapterStaff.OnStaffQuitClickListener() {
            @Override
            public void onStaffQuitClick(final StaffBean bean) {
                DialogMakeSure dialog = new DialogMakeSure(mContext);
                dialog.getDialog("是否离职该员工?").show();
                dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
                    @Override
                    public void onSure(DialogInterface dialog, int which) {
                        sendRequestStaffQuit(bean.getId());
                    }

                    @Override
                    public void onCancel(DialogInterface dialog, int which) {
                    }
                });

            }

            @Override
            public void onStaffEdit(StaffBean bean) {
                start(FragmentAddEditShopManager.newInstance(bean, AppConstant.STATE_EDIT_SHOP_GUIDE));
            }

            @Override
            public void onPhoneClick(String phone) {
                PhoneUtils.dial(phone);
            }
        });

        ctb.setTvTitle("门店详情");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterStaff.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentStoreDetail.class.getName();
    }

    @Override
    public void onRefresh() {
        mAdapterStaff.setEnableLoadMore(false);
        if (mError) {
            mAdapterStaff.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterStaff.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    private void bindStoreBean(StoreBean storeBean) {
        tvShopName.setText(storeBean.getStoreName());
        tvPhone.setText(storeBean.getMobileNum());
        tvShopAddr.setText(storeBean.getConnectAddress());
        ImageLoaderUtils.getGlideManager().asBitmap().load(storeBean.getStoreLogoUrl()).apply(ImageLoaderUtils.getSGCommonGlideOption(12)).into(ivShopLogo);
    }

    private void initRequest() {
        sendRequestGetStaffList();
    }

    private void sendRequestGetStaffList() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        if (jsonObject.has("merStore")) {
                            StoreBean storeBean = JsonUtil.getGson().fromJson(jsonObject.getString("merStore"), StoreBean.class);
                            bindStoreBean(storeBean);
                        }
                        JSONArray jsonArray = jsonObject.getJSONArray("storeStaffList");
                        if (jsonArray.length() != 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                StaffBean staffBean = JsonUtil.getGson().fromJson(jsonArray.getString(i), StaffBean.class);
                                mStaffList.add(staffBean);
                            }
                            mAdapterStaff.setNewData(mStaffList);
                        } else {
                            bindEmpty();
                        }
                        finishRefresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getStaffListInStore(new SimpleLbObserver(listener, otherListener), storeBean.getStoreCode(),this,FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestStaffQuit(int id) {
        HashMap hashMap = new HashMap();
        hashMap.put("id", id);
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ToastUtils.showShort("员工离职成功");
                    refresh();
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {

            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("员工离职失败" + error);
            }
        };
        ApiMethodBoss.staffQuit(new SimpleLbObserver(listener, errorListener), body,this, FragmentEvent.DESTROY_VIEW);
    }

    @OnClick(R.id.layout_add_shop_manager)
    void addShopManager() {
        start(FragmentAddEditShopManager.newInstance("" + storeBean.getStoreCode(), AppConstant.STATE_ADD_SHOP_GUIDE));
    }

    @OnClick(R.id.layout_store_detail)
    void storeDetail() {
        start(FragmentAddEditShop.newInstance(storeBean.getId()));
    }

    private void bindEmpty() {
        mStaffList.clear();
        mAdapterStaff.setNewData(mStaffList);

        mNoData = true;
        onRefresh();
    }

    private void refresh() {
        mStaffList = new ArrayList<>();
        sendRequestGetStaffList();
    }

    @Subscribe
    public void onAddGuide(AddGuideEvent event) {
        refresh();
    }

    @Subscribe
    public void onEditShop(EditShopEvent event) {
        refresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
